package com.niiwoo.civet.account.service.local.openAccount2.order;

import com.niiwoo.civet.account.constant.AccountRegisterErrorCode;
import com.niiwoo.civet.account.dao.entity.AccountBase;
import com.niiwoo.civet.account.dao.entity.ActivateAccountOrder;
import com.niiwoo.civet.account.dao.entity.OpenAccountRecord;
import com.niiwoo.civet.account.dao.mapper.AccountBaseMapperExt;
import com.niiwoo.civet.account.dao.mapper.ActivateAccountOrderMapperExt;
import com.niiwoo.civet.account.enums.AccountActiveEnum;
import com.niiwoo.civet.account.enums.ActivateAccountOrderStatusEnum;
import com.niiwoo.civet.account.enums.OpenAccountRecordStatusEnum;
import com.niiwoo.civet.account.service.local.AccountService;
import com.niiwoo.civet.account.service.local.openAccount2.dto.ActivateUpdateRequest;
import com.niiwoo.civet.account.service.local.openAccount2.dto.CreateRequest;
import com.niiwoo.civet.account.service.local.openAccount2.dto.OrderBasicInfo;
import com.niiwoo.civet.account.service.local.openAccount2.dto.UpdateRequest;
import com.niiwoo.civet.account.service.local.openAccount2.lanmao.LanMaoHelper;
import com.niiwoo.civet.account.service.local.openAccount2.type.ActivateTypeable;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.lanmao.component.LanMaoSequence;
import com.niiwoo.tripod.lanmao.enums.AuthenticateValidTypeEnum;
import com.niiwoo.tripod.lanmao.enums.UserAuthorizationEnum;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import java.util.Date;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ActivateOrderHandler implements OpenAccountOrderOperation<ActivateAccountOrder>, ActivateTypeable {


    @Autowired
    AccountService accountService;

    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    LanMaoSequence lanMaoSequence;
    @Autowired
    PrivacyMasks privacyMasks;
    @Autowired
    private ActivateAccountOrderMapperExt activateAccountOrderMapperExt;

    @Override
    public boolean create(ActivateAccountOrder activateAccountOrder) {
        return activateAccountOrderMapperExt.insertSelective(activateAccountOrder) > 0;
    }

    @Override
    public boolean update(ActivateAccountOrder activateAccountOrder) {
        return activateAccountOrderMapperExt.updateByPrimaryKeySelective(activateAccountOrder) > 0;
    }

    @Override
    public ActivateAccountOrder getByRequestNo(String requestNo) {
        return activateAccountOrderMapperExt.selectByRequestNo(requestNo);
    }

    @Override
    public boolean isSuccess(ActivateAccountOrder activateAccountOrder) {
        return ActivateAccountOrderStatusEnum.except(activateAccountOrder.getStatus(), ActivateAccountOrderStatusEnum.SUCCESS);
    }

    @Override
    public ActivateAccountOrder getNewOrder(CreateRequest request, OpenAccountRecord record) {
        // 待激活账户
        AccountBase accountBase = Optional.ofNullable(accountService.getNiiwooAccount(record.getUserId(), UserRoleEnum.enumOf(record.getAccountRole())))
                .filter(a -> a.getImportUserActiva().equals(AccountActiveEnum.UNACTIVATED.getValue()))
                .orElseThrow(() -> new BizException(AccountRegisterErrorCode.ACCOUNT_NOT_EXISTS));
        // 开户记录必须使用待激活账户编号
        record.setAccountNo(accountBase.getAccountNo());
        // 权限
        Set<String> authSet = LanMaoHelper.getAuthSetByRole(request.getRole());
        if (accountBase.getTender() == (byte) 1) {
            authSet.add(UserAuthorizationEnum.TENDER.name());
        }
        if (accountBase.getRepayment() == (byte) 1) {
            authSet.add(UserAuthorizationEnum.REPAYMENT.name());
        }
        if (accountBase.getCreditAssignment() == (byte) 1) {
            authSet.add(UserAuthorizationEnum.CREDIT_ASSIGNMENT.name());
        }
        if (accountBase.getCompensatory() == (byte) 1) {
            authSet.add(UserAuthorizationEnum.COMPENSATORY.name());
        }
        if (accountBase.getWithdraw() == (byte) 1) {
            authSet.add(UserAuthorizationEnum.WITHDRAW.name());
        }
        if (accountBase.getRecharge() == (byte) 1) {
            authSet.add(UserAuthorizationEnum.RECHARGE.name());
        }
        // 创建订单
        ActivateAccountOrder order = new ActivateAccountOrder();
        order.setId(snowflakeIdWorker.nextId());
        order.setRequestNo(lanMaoSequence.getRequestNo());
        order.setAccountNo(accountBase.getAccountNo());
        order.setUserId(accountBase.getUserId());
        order.setUserRole(accountBase.getAccountRole());
        order.setCheckType(AuthenticateValidTypeEnum.LIMIT.getValue());
        order.setAuthList(String.join(",", authSet));
        order.setStatus(ActivateAccountOrderStatusEnum.PROCESSING.getValue());
        order.setCreateTime(new Date());
        return order;
    }

    @Override
    public OrderBasicInfo getOrderBasicInfo(ActivateAccountOrder activateAccountOrder) {
        OrderBasicInfo orderBasicInfo = new OrderBasicInfo();
        orderBasicInfo.setUserId(activateAccountOrder.getUserId());
        orderBasicInfo.setRole(activateAccountOrder.getUserRole());
        orderBasicInfo.setAccountNo(activateAccountOrder.getAccountNo());
        orderBasicInfo.setAuthList(activateAccountOrder.getAuthList());
        orderBasicInfo.setIsInitAccount(false);
        return orderBasicInfo;
    }

    @Override
    public ActivateAccountOrder getUpdateOrder(ActivateAccountOrder oldOrder, UpdateRequest request, OpenAccountRecordStatusEnum recordStatus) {
        ActivateUpdateRequest activateUpdateRequest = (ActivateUpdateRequest) request;
        ActivateAccountOrder updateOrder = new ActivateAccountOrder();
        updateOrder.setId(oldOrder.getId());
        if (activateUpdateRequest.getAccessType() != null) {
            updateOrder.setCheckType(activateUpdateRequest.getAccessType().getValue());
        }
        if (StringUtils.isNotBlank(activateUpdateRequest.getBankCardNo())) {
            updateOrder.setBankCardNo(privacyMasks.encryptPrivacy(activateUpdateRequest.getBankCardNo()));
        }
        if (StringUtils.isNotBlank(activateUpdateRequest.getBankCardMobileNo())) {
            updateOrder.setBankCardMobileNo(privacyMasks.encryptPrivacy(activateUpdateRequest.getBankCardMobileNo()));
        }
        if (activateUpdateRequest.getBankCode() != null) {
            updateOrder.setBankCode(activateUpdateRequest.getBankCode().getCode());
        }
        updateOrder.setErrorCode(activateUpdateRequest.getErrorCode());
        updateOrder.setErrorMessage(activateUpdateRequest.getErrorMessage());
        switch (recordStatus) {
            case SUCCESS: {
                updateOrder.setStatus(ActivateAccountOrderStatusEnum.SUCCESS.getValue());
            }
            break;
            case AUDIT_RETURN: {
                updateOrder.setStatus(ActivateAccountOrderStatusEnum.AUDIT_RETURN.getValue());
            }
            break;
            case AUDIT_REJECT: {
                updateOrder.setStatus(ActivateAccountOrderStatusEnum.AUDIT_REJECT.getValue());
            }
            break;
            case PROCESSING: {
                updateOrder.setStatus(ActivateAccountOrderStatusEnum.PROCESSING.getValue());
            }
            break;
            case AUDITING: {
                updateOrder.setStatus(ActivateAccountOrderStatusEnum.AUDITING.getValue());
            }
            break;
            case EXPIRED:
            case FAILURE: {
                updateOrder.setStatus(ActivateAccountOrderStatusEnum.FAILURE.getValue());
            }
            break;
            default:
                updateOrder.setStatus(oldOrder.getStatus());
        }
        return updateOrder;
    }


}
